import type { Directive } from 'vue'

interface TooltipHost extends HTMLElement {
  _tooltip?: HTMLDivElement
  _tooltipHandlers?: {
    showTooltip: () => void
    hideTooltip: () => void
  }
}

export const vTooltip: Directive<TooltipHost, string> = {
  mounted(el, binding) {
    // arg指令参数（:），modifiers指令修饰符(.)
    const { value, arg = 'top', modifiers } = binding

    // 创建工具提示元素
    const tooltip = document.createElement('div')
    tooltip.className = 'tooltip'
    tooltip.textContent = value
    tooltip.style.cssText = `
      position: absolute;
      background: #333;
      color: white;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 14px;
      z-index: 1000;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.2s;
      width: 120px;
    `

    // 根据参数设置位置
    if (arg === 'bottom') {
      tooltip.style.top = '100%'
      tooltip.style.left = '50%'
      tooltip.style.transform = 'translateX(-50%)'
      tooltip.style.marginTop = '8px'
    } else if (arg === 'left') {
      tooltip.style.right = '100%'
      tooltip.style.top = '50%'
      tooltip.style.transform = 'translateY(-50%)'
      tooltip.style.marginRight = '8px'
    } else if (arg === 'right') {
      tooltip.style.left = '100%'
      tooltip.style.top = '50%'
      tooltip.style.transform = 'translateY(-50%)'
      tooltip.style.marginLeft = '8px'
    } else {
      tooltip.style.bottom = '100%'
      tooltip.style.left = '50%'
      tooltip.style.transform = 'translateX(-50%)'
      tooltip.style.marginBottom = '8px'
    }

    // 根据修饰符设置样式
    if (modifiers.large) {
      tooltip.style.fontSize = '16px'
      tooltip.style.padding = '12px 16px'
    }

    if (modifiers.success) {
      tooltip.style.background = '#28a745'
    } else if (modifiers.warning) {
      tooltip.style.background = '#ffc107'
      tooltip.style.color = '#333'
    } else if (modifiers.danger) {
      tooltip.style.background = '#dc3545'
    }

    el.appendChild(tooltip)
    el.style.position = 'relative'

    // 显示/隐藏工具提示
    const showTooltip = () => {
      tooltip.style.opacity = '1'
    }

    const hideTooltip = () => {
      tooltip.style.opacity = '0'
    }

    el.addEventListener('mouseenter', showTooltip)
    el.addEventListener('mouseleave', hideTooltip)

    // 保存引用以便清理
    el._tooltip = tooltip
    el._tooltipHandlers = { showTooltip, hideTooltip }
  },

  beforeUnmount(el) {
    if (el._tooltip) {
      el.removeChild(el._tooltip)
    }
    if (el._tooltipHandlers) {
      const { showTooltip, hideTooltip } = el._tooltipHandlers
      el.removeEventListener('mouseenter', showTooltip)
      el.removeEventListener('mouseleave', hideTooltip)
    }
  },
}
